package main

import (
	"database/sql"
	"fmt"
	"io"
	"os"

	_ "github.com/go-sql-driver/mysql"
	"gopkg.in/yaml.v3"
)

// 准备结构体，用于绑定读取的数据
type Database struct {
	// 设置要解析的yaml文件中的键名称
	User     string `yaml:"user"`
	Password string `yaml:"password"`
	Host     string `yaml:"host"`
	Port     int    `yaml:"port"`
	Dbname   string `yaml:"dbname"`
}
type Config struct {
	Database `yaml:"database"`
}

func main() {
	// 读取配置文件
	file, _ := os.Open("config.yaml")
	data, err := io.ReadAll(file)
	if err != nil {
		panic(err)
	}
	// fmt.Println(data)
	// 定义一个结构体变量
	var config Config
	// 将读取的yaml文件解析到config中
	err = yaml.Unmarshal(data, &config)
	if err != nil {
		panic(err)
	}
	// fmt.Println(config)
	database := config.Database
	// dsn := "root:123456@tcp(192.168.88.11:3306)/tedu"
	// 拼接连接信息
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s", database.User, database.Password, database.Host, database.Port, database.Dbname)
	// 创建MySQL连接对象
	db, err := sql.Open("mysql", dsn)
	if err != nil {
		panic(err)
	}
	// 建立连接
	err = db.Ping()
	if err != nil {
		panic(err)
	}
	// 1.插入数据
	// insert_sql := "insert into student(name, grade, age) values(?,?,?)"
	// db.Exec(insert_sql, "小明", "三年级一班", 10)
	// db.Exec(insert_sql, "小明", "三年级一班", 9)
	// db.Exec(insert_sql, "小明", "三年级一班", 10)
	// 2.查询数据
	select_sql := "select name,grade,age from student where id=?"
	row := db.QueryRow(select_sql, 1)
	var name, grade string
	var age int
	// 绑定到指定的变量
	err = row.Scan(&name, &grade, &age)
	// fmt.Println(err)
	fmt.Println(name, grade, age)
}
